package com.fast.framework.web.plugin.redis.serializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.nustaq.serialization.FSTObjectInput;
import org.nustaq.serialization.FSTObjectOutput;

/**
 * FstSerializer
 * @author zengjintao
 * @version 1.0
 * @createTime 2017年11月3日下午3:31:43
 */
public class FstSerializer implements ISerializer{

	@Override
	public byte[] valueToBytes(Object value) {
		FSTObjectOutput fstOut = null;
		try {
			ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
			fstOut = new FSTObjectOutput(bytesOut);
			fstOut.writeObject(value);
			fstOut.flush();
			return bytesOut.toByteArray();
		} 
		catch (Exception e) {
			throw new RuntimeException(e);
		}
		finally {
			if(fstOut != null)
				try {fstOut.close();} catch (IOException e) {e.printStackTrace();}
		}
	}
	
	@Override
	public Object bytesToObject(byte[] bytes){
		if(bytes == null || bytes.length == 0)
			return null;
		
		FSTObjectInput fstIn = null;
		try {
			ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytes);
			fstIn = new FSTObjectInput(bytesIn);
			return fstIn.readObject();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally {
			if(fstIn != null){
				try {fstIn.close();} catch (IOException e) {e.printStackTrace();}
			}
		}
	}
}
